const socket = require('socket.io');
const http = require('http');
const server = http.createServer();

const io = socket(server, {
  cors: {
    origin: '*' // 配置跨域
  }
});

io.on('connection', (socket) => {
  console.log('用户连接成功');
  socket.emit('connectionSuccess')
  // 监听加入房间的事件
  socket.on('joinRoom', (roomId) => {
    console.log('用户加入房间', roomId);
    socket.join(roomId);
  })
  // 监听事件A发送视频请求
  socket.on('callRemote', (roomId) => {
    io.to(roomId).emit('callRemote')
  })
  // B同意接受视频请求
  socket.on('acceptCall', (roomId) => {
    io.to(roomId).emit('acceptCall')
  })
  // A发送offer给B
  socket.on('sendOffer', ({ roomId, offer }) => {
    io.to(roomId).emit('sendOffer', offer)
  })
  //// B发送Answer给A 
  socket.on('sendAnswer', ({ roomId, answer }) => {
    io.to(roomId).emit('sendAnswer', answer)
  })
  // 收到candidate信息
  socket.on('sendCandidate', ({ roomId, candidate }) => {
    io.to(roomId).emit('sendCandidate', { candidate });
  });
  //用户断开链接
  socket.on('disconnect', () => {
    console.log('用户断开连接');
    const rooms = Array.from(socket.rooms);
    rooms.forEach(roomId => {
      if (roomId !== socket.id) {
        io.to(roomId).emit('userLeft', { roomId, userId: socket.id });
        socket.leave(roomId);
      }
    });
  });
  // 用户主动挂断
  socket.on('hangUp', ({ roomId }) => {
    console.log('用户主动断开连接');
    io.to(roomId).emit('userHangUp', { roomId, userId: socket.id });
    socket.leave(roomId);
  });


})





server.listen(3000, () => {
  console.log('服务启动成功');
})